import os
import json
import re
import csv
from collections import defaultdict

def extract_device_info(content):
    """从文件内容中提取品牌、型号和UID信息"""
    brand = None
    model = None
    uid = None
    
    # 提取品牌信息
    brand_match = re.search(r'ro\.product\.brand["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    # 提取型号信息
    model_match = re.search(r'ro\.product\.model["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    # 提取UID信息（新增）
    uid_match = re.search(r'uid["\']?\s*[:=]\s*["\']?([^\s,}]+)', content)
    
    if brand_match:
        brand = brand_match.group(1).strip('"\'')
    if model_match:
        model = model_match.group(1).strip('"\'')
    if uid_match:
        uid = uid_match.group(1).strip('"\'')
    
    return brand, model, uid  # 返回三个值

def process_dat_files(directory):
    """处理目录中的所有DAT文件并返回分类结果"""
    # 使用列表存储所有记录（包含重复）
    all_records = []
    # 按品牌分类的型号列表（包含重复）
    brand_models = defaultdict(list)
    
    file_count = 0
    error_count = 0
    
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(".dat"):
                file_path = os.path.join(root, file)
                file_count += 1
                
                try:
                    with open(file_path, "r", encoding="utf-8") as f:
                        content = f.read()
                    
                    # 获取品牌、型号和UID
                    brand, model, uid = extract_device_info(content)
                    
                    if brand and model:
                        # 使用UID作为唯一标识（如无UID则使用文件名）
                        unique_id = uid if uid else os.path.splitext(file)[0]
                        
                        # 添加到所有记录列表
                        all_records.append({
                            "brand": brand,
                            "model": model,
                            "uid": unique_id,
                            "source_file": file
                        })
                        
                        # 添加到品牌分类列表
                        brand_models[brand].append((model, unique_id))
                    else:
                        error_count += 1
                        print(f"⚠️ 文件 {os.path.basename(file_path)} 中缺少品牌或型号信息")
                
                except Exception as e:
                    error_count += 1
                    print(f"❌ 处理文件 {file_path} 时出错: {str(e)}")
    
    # 返回所有记录和分类结果
    return all_records, brand_models, file_count, error_count

def save_to_csv(records, output_file):
    """将记录保存为CSV文件"""
    with open(output_file, 'w', newline='', encoding='utf-8') as csvfile:
        fieldnames = ['brand', 'model', 'uid', 'source_file']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        
        writer.writeheader()
        for record in records:
            writer.writerow(record)
    
    print(f"✅ 结果已保存至: {os.path.abspath(output_file)}")

# 主执行逻辑
if __name__ == "__main__":
    directory = "data_2"
    output_csv = "device_records.csv"
    
    # 处理文件
    all_records, brand_models, total_files, error_files = process_dat_files(directory)
    
    # 打印统计信息
    print(f"\n{'='*50}")
    print(f"📊 处理完成! 扫描文件: {total_files} | 成功解析: {len(all_records)} | 错误文件: {error_files}")
    print(f"🏷️ 发现品牌数量: {len(brand_models)} | 总记录数: {len(all_records)}")
    print('='*50)
    

    
    # 保存为CSV文件
    save_to_csv(all_records, output_csv)
    